package com.badibadi.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.badibadi.activity.LogReadingActivity;
import com.badibadi.infos.RecordModel;
import com.badibadi.infos.Results;
import com.badibadi.mytools.BitmapHelp;
import com.badibadi.mytools.CommonUtils;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.JSONUtils;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.StringUtils;
import com.badibadi.mytools.Utils;
import com.badibadi.mytools.ViewHolder;
import com.badibadi.uniclubber.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.view.my_view.XListView;
import com.view.my_view.XListView.IXListViewListener;

//f_m_i_l_overtime
public class RecordFragment0 extends BaseFragment implements IXListViewListener {
	// TODO Auto-generated method stub iv_collect
	private String TAG = "AfterLandingMessageItem00";

	static RecordFragment0 fragment;
	private XListView1Adapter____1 x1Adapter;
	private XListView xListView1;
	private int Page;
	private boolean isXiala = false;
	private boolean isShangla = false;
	private Results results, results2, results3;
	private List<RecordModel> mList;
	private List<RecordModel> list;
	private int pageNum = 10;
	private String showType;
	private int type = 0;// 0最新 1 最热 2 投票排行
	private String uid = "26";
	private String fid = "26";
	private String j = "";
	int pos_ = -1;
	private int pos = 0;
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				Utils.ExitPrgress(getActivity());

				try {
					onLoad();
					Utils.showMessage(getActivity(),
							getResources().getString(R.string.l_net_error));
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 2:
				try {
					xListView1.requestLayout();
					mList.addAll(list);
					x1Adapter.notifyDataSetChanged();
					onLoad();
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 3:
				Utils.ExitPrgress(getActivity());

				try {
					onLoad();
					Utils.showMessage(getActivity(),
							getResources().getString(R.string.l_xa10));
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 4:
				Utils.ExitPrgress(getActivity());
				try {
					Utils.showMessage(getActivity(), results2.getRetmsg());
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 5:
				Utils.ExitPrgress(getActivity());
				try {
					Utils.showMessage(getActivity(), results3.getRetmsg());
					if (results3.isRet()) {
						int d = Integer.valueOf(mList.get(pos).getVote());
						mList.get(pos).setVote(++d + "");
						mList.get(pos).setVoted("1");
						x1Adapter.notifyDataSetChanged();
					}
					// else {
					// int d = Integer.valueOf(mList.get(pos).getVote());
					// if (d > 0) {
					// mList.get(pos).setVote(--d + "");
					// } else {
					// mList.get(pos).setVote(0 + "");
					// }
					// x1Adapter.notifyDataSetChanged();
					// }
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 9://
				Utils.ExitPrgress(getActivity());
				try {

					Utils.showMessage(getActivity(),
							getResources().getString(R.string.l_xb12));
				} catch (Exception e) {

				}
				break;
			case 10:// 收藏成功
				Utils.ExitPrgress(getActivity());
				try {

					Utils.showMessage(
							getActivity(),
							getResources().getString(
									R.string.wx_shoucang_success));

					if (pos_ != -1) {

						// mList.get(pos_).setIs_collect("1");

						mList.get(pos_).setCollect(
								""
										+ (Integer.parseInt(mList.get(pos_)
												.getCollect()) + 1));
						// user_trends.get(pos_).setIs_collected(1);
						// user_trends.get(pos_).setCollect(""+(Integer.parseInt((user_trends.get(pos_).getCollect()))+1));
						x1Adapter.notifyDataSetChanged();
						pos_ = -1;
					}
				} catch (Exception e) {

				}
				break;
			case 11://
				Utils.ExitPrgress(getActivity());
				try {

					Utils.showMessage(getActivity(),
							getResources().getString(R.string.wx_txt_70));
				} catch (Exception e) {

				}
				break;
			case 12:
				try {
					mList.clear();
					Page = 1;
					LoadingInterNet(Page);
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			default:
				break;
			}
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Page = 0;
		uid = getArguments().getString("uid", "1");
		fid = getArguments().getString("fid", "-1");
		showType = getArguments().getString("showType", "myRecord");
		mList = new ArrayList<RecordModel>();
		x1Adapter = new XListView1Adapter____1();

		// LoadingInterNet(Page);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.xlistview, null);
		InitMyXListView1(view);
		return view;
	}

	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		if (Constants.is_shuaxin) {
			mHandler.sendEmptyMessageDelayed(12, 700);
			Constants.is_shuaxin = false;
		}
	}

	public void InitMyXListView1(View view) {
		// Constants.Invite_handler = mHandler;
		xListView1 = (XListView) view.findViewById(R.id.my_xListView1);
		xListView1.setXListViewListener(this);
		xListView1.setPullLoadEnable(true);
		xListView1.setPullRefreshEnable(true);
		xListView1.setDivider(null);
		xListView1.setAdapter(x1Adapter);
		xListView1.startLoadMore();
	}

	private void LoadingInterNet(final int page) {
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				list = new ArrayList<RecordModel>();
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("uid", uid);
//				   
//				if (fid.equals("-1") != true) {
//					map.put("fid", fid);
//				}
				map.put("fid", Utils.getUid(getActivity()));
				map.put("type", type);
				map.put("page", page);
				map.put("pageNum", pageNum);
				map.put("showType", showType);
//				   ("记录提交上去的数据:" + map.toString());
				String invite_content = Utils.sendRequest(map,
						Constants.BadiUrl + "record");
				//    
				if (invite_content != null) {
					results = Utils.checkResult_NNN(getActivity(),
							invite_content);
					if (results != null && !results.getRetmsg().equals("null")) {
						//    
//						   ("我是解析出来的数据:" + results.getRetmsg());
						try {
							list = JSONUtils.getListByJsonString(
									results.getRetmsg(), RecordModel.class);
							// mList.addAll(list);
							if (isXiala == false)
								mHandler.sendEmptyMessage(2);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							   
						}
					} else {
						if (page > 1) {
							--Page;
						} else {
							Page = 1;
						}
						mHandler.sendEmptyMessage(3);
					}
				} else {
					if (page > 1) {
						--Page;
					} else {
						Page = 1;
					}
					mHandler.sendEmptyMessage(1);
				}

			}
		});
	}

	public static RecordFragment0 getInstance() {
		if (fragment == null) {
			return new RecordFragment0();
		}
		return fragment;
	}

	protected void onLoad() {
		xListView1.stopRefresh();
		xListView1.stopLoadMore();
		xListView1.setRefreshTime(""+getResources().getString(R.string.ganggang));
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		mList.clear();
		Page = 1;
		LoadingInterNet(Page);

	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		// LoadingInterNet(++Page);

		// if(isShangla==false)
		// {
		// isShangla=true;

		LoadingInterNet(++Page);
		// }

	}

	private void vote(final String uid, final String rid) {
		Utils.showPrgress(getActivity());
		MyThreadTool.fixedThreadPool.execute(new Runnable() {

			@Override
			public void run() {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("rid", rid);
				map.put("uid", uid);
//				   ("投票数据提交的是:" + map.toString());
				String content = Utils.sendRequest(map, Constants.BadiUrl
						+ "vote");
				if (content != null) {
//					   ("返回的投票数据是:" + content);
					results3 = Utils.checkResult_NNN(getActivity(), content);
					if (results3 != null
							&& !results3.getRetmsg().equals("null")) {
						mHandler.sendEmptyMessage(5);
					} else {
						mHandler.sendEmptyMessage(3);
					}
				} else {
					mHandler.sendEmptyMessage(1);
				}
			}
		});
	}

	class XListView1Adapter____1 extends BaseAdapter {
		private DisplayImageOptions options;

		public XListView1Adapter____1() {
			options = new DisplayImageOptions.Builder()
					.showStubImage(R.drawable.ic_stub)
					.showImageForEmptyUri(R.drawable.noimage)
					.showImageOnFail(R.drawable.noimage).cacheInMemory()
					.cacheOnDisc().displayer(new RoundedBitmapDisplayer(5))
					.build();
		}

		@Override
		public int getCount() {
			return mList.size();
		}

		@Override
		public Object getItem(int position) {
			return mList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {

			if (convertView == null) {
				convertView = ViewHolder
						.buildView(
								getActivity(),
								R.layout.fragment_myrecordlist0_import_layout_0,
								parent);
			}
			ViewHolder viewHolder = (ViewHolder) convertView.getTag();

			// 地址
			TextView address = viewHolder
					.getViewById(R.id.fragment_myrl_import_adress_textview);
			address.setText("" + mList.get(position).getName());
			// 开始时间
			TextView startTime = viewHolder.getViewById(R.id.f_m_i_l_starttime);
			if (!StringUtils.isEmpty(mList.get(position).getStart_time())) {
				startTime.setText("" + mList.get(position).getStart_time());
			}
			// 结束时间
			TextView overTime = viewHolder.getViewById(R.id.f_m_i_l_overtime);
			if (!StringUtils.isEmpty(mList.get(position).getEnd_time())) {
				overTime.setText("" + mList.get(position).getEnd_time());
				// System.out
				// .println("结束时间是:" + mList.get(position).getEnd_time());
			}
			// 头像
			ImageView headimg = viewHolder.getViewById(R.id.f_m_i_l_touxiang);
			try {
				ImageLoader.getInstance().displayImage(
						Constants.BadiDownImgUrl + "/"
								+ mList.get(position).getHead()
								+ Constants.appPhoto4img, headimg, options);
			} catch (Exception e) {
				// TODO: handle exception
			}
			// 背景图
			ImageView background_img = viewHolder
					.getViewById(R.id.fragment_myrl_import_background_img);

			try {
				// ImageLoader.getInstance().displayImage(
				// Constants.BadiDownImgUrl + "/"
				// + mList.get(position).getImage()
				// + Constants.Appactivitycover, background_img,
				// options);
				new BitmapHelp().displayImage(getActivity(), background_img,
						Constants.BadiDownImgUrl + "/"
								+ mList.get(position).getImage()
								+ Constants.Appactivitycover);
			} catch (Exception e) {
				// TODO: handle exception
			}
			// 点击背景图进入到记录阅读
			background_img.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					String rid = mList.get(position).getRid();
					Intent intent = new Intent(getActivity(),
							LogReadingActivity.class);
					intent.putExtra("rid", rid);
					intent.putExtra("jilu_fabiao_uid", mList.get(position)
							.getUid());// 记录发起者的id
					getActivity().startActivity(intent);
				}
			});

			// 名字
			TextView myname = viewHolder.getViewById(R.id.f_m_i_l_name);
			myname.setText("" + mList.get(position).getNickName());
			// 投票数量
			TextView votenumber = viewHolder
					.getViewById(R.id.f_m_i_l_vote_number);
			votenumber.setText("" + mList.get(position).getVote());
			// 观看数量
			TextView seenumber = viewHolder.getViewById(R.id.f_m_i_l_see);
			seenumber.setText("" + mList.get(position).getView());
			// 评论数量
			TextView pinlun = viewHolder.getViewById(R.id.f_m_i_l_say);
			pinlun.setText("" + mList.get(position).getDiscuss());
			// 收藏(心的标识)
			TextView collection = viewHolder.getViewById(R.id.f_m_i_l_xin);
			collection.setText("" + mList.get(position).getCollect());
			// 收藏按钮
			ImageView iv_collect = viewHolder.getViewById(R.id.iv_collect);

			iv_collect.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					
					pos_ = position;
					collect("0", mList.get(position).getUid(),
							mList.get(position).getRid(), "record");
				}
			});
			// if (mList.get(position).getIs_collect().equals("0")) {
			// iv_collect.setSelected(false);
			//
			// } else {
			// iv_collect.setSelected(true);
			// }

			Button f_m_i_l_toupiao = viewHolder
					.getViewById(R.id.f_m_i_l_toupiao);
			if (mList.get(position).getIs_vote() != null
					&& mList.get(position).getIs_vote().equals("1")) {
				f_m_i_l_toupiao.setVisibility(View.VISIBLE);// 权限为可以投票
				votenumber.setVisibility(View.VISIBLE);
				if (mList.get(position).getVoted().equals("0")) {
					// 可投票
					f_m_i_l_toupiao.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View arg0) {
							if (Utils.getUid(getActivity()) != null) {

								pos = position;
								vote(Utils.getUid(getActivity()),
										mList.get(position).getRid());
							} else {
								Toast.makeText(
										getActivity(),
										getResources().getString(
												R.string.l_xb10), 0).show();
							}
						}
					});
				} else if (mList.get(position).getVoted().equals("1")) {
					// 已经投了票了
					f_m_i_l_toupiao
							.setBackgroundResource(R.drawable.yuanpan_selector);
				}
			} else if (mList.get(position).getIs_vote() != null
					&& mList.get(position).getIs_vote().equals("2")) {
				f_m_i_l_toupiao.setVisibility(View.GONE);// 权限为不可投票
				votenumber.setVisibility(View.GONE);
			}
			return convertView;
		}

		/**
		 * 用户+俱乐部 收藏的操作接口 提交方式GET
		 * 
		 * @param $uid
		 *            ;//收藏人的id
		 * @param $cid
		 *            ;//俱乐部收藏-------仅有record，humor_trends 这两种收藏方式，当为个人收藏时，值为0
		 * @param $nuid
		 *            ;//被收藏内容所属的用户id
		 * @param $nid
		 *            ;//被收藏的内容id
		 * @param $type
		 *            ;//被收藏的类型-----个人（3种）：photo_img，record，humor_trends
		 *            俱乐部（2种）：record，humor_trends
		 */
		public void collect(String cid, String nuid, String neirong_id,
				String type) {// Constants.BadiUrl+
								// "praise_operate?uid="+uid+"&nid="+nid+"&nuid="+nuid+"&type="+type
			/*
			 * 用户收藏的操作接口 提交方式GET
			 * 
			 * @param $uid;//收藏人的id @param $nuid;//被收藏内容所属的用户id
			 * 
			 * @param $nid;//被收藏的内容id @param
			 * $type;//被收藏的类型（photo_img，record，humor_trends）
			 */
			String uid = Utils.getUid(getActivity());
			Utils.showPrgress(getActivity());
			CommonUtils.CommomGetfunction(getActivity(), Constants.BadiUrl
					+ "collect_operate?uid=" + uid + "&cid=" + cid + "&nuid="
					+ nuid + "&nid=" + neirong_id + "&type=" + type, mHandler,
					1, 9, 10, 11);
		}

	}

}
